package com.itfreer.data.check;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.itfreer.data.check.entity.CheckConfigEntity;
import com.itfreer.data.check.entity.CheckHistoryEntity;
import com.itfreer.utils.ResponseEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 检查结果服务
 */
@RestController
@RequestMapping("/checkservice")
@Api("检查服务")
public class RestCheckService {

	@Autowired
	private CheckHistoryService checkHistoryService;
	@Autowired
	private CheckConfigService checkConfigService;

	@Autowired(required = false)
	private CheckService service;

	@ApiOperation(value = "单项数据检查")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "id", value = "检查数据ID", paramType = "path", required = true),
			@ApiImplicitParam(name = "checktypeid", value = "配置ID", paramType = "path", required = true),
			@ApiImplicitParam(name = "tacheid", value = "检查环节", paramType = "path", required = true),
			@ApiImplicitParam(name = "entity", value = "检查数据", paramType = "body", required = true) })
	@PostMapping(value = "/check/{id:.+}/{checktypeid:.+}/{tacheid:.+}", produces = "application/json")
	public ResponseEntity<CheckHistoryEntity> check(@PathVariable("id") String id,
			@PathVariable("checktypeid") String checkTypeID, @PathVariable("tacheid") Integer tacheid,
			@RequestBody Map<String, Object> entity) {

		Map<String, Object> where = new HashMap<>();
		where.put("dataid", id);
		List<CheckHistoryEntity> checkHis = checkHistoryService.getEntitys(where, null);
		CheckHistoryEntity checkResult = null;
		if (checkHis != null && checkHis.size() > 0) {
			checkResult = checkHis.get(0);
		} else {
			CheckConfigEntity config = checkConfigService.getEntity(checkTypeID);
			checkResult = new CheckHistoryEntity();
			checkResult.setName(config.getName());
			checkResult.setDataid(id);
		}
		checkResult = service.check(checkResult, entity, checkTypeID, tacheid);
		return new ResponseEntity<>(checkResult);
	}
}
